// pages/seller/seller.js
var app = getApp();
const util = require('../../utils/util.js');
var model = require('../../utils/model/model.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    httpApiImg: app.globalData.httpApiImg,
    userInfo: '',
    isAgree: false,
    formlist: [
      { isrequire: true, value: '', label: '商家类别', valueType: 'text', key: 'shopType', tips: '请选择', type: 'select', data: [] },
      { isrequire: true, value: '', label: '商家名称', valueType: 'text', key: 'shopName', tips: '请填写', type: 'input' },
      { isrequire: true, value: '', label: '行业分类', valueType: 'text', key: 'industry', tips: '请选择', type: 'select', data: [] },
      { isrequire: true, value: ['江苏省','连云港市','连云区'], label: '所属区域', valueType: 'text', key: 'region', tips: '请选择', type: 'select', mode: 'region' },
      { isrequire: true, value: '', label: '详细地址', valueType: 'text', key: 'adress', tips: '请填写', type: 'input' },
      { isrequire: true, value: '', label: '开始营业时间', valueType: 'text', key: 'sopenTime', tips: '请填写', type: 'select', mode:'time' },
      { isrequire: true, value: '', label: '结束营业时间', valueType: 'text', key: 'eopenTime', tips: '请填写', type: 'select', mode: 'time' },
      { isrequire: true, value: '', label: '联系电话', valueType: 'number', key: 'contactNum', tips: '请填写', type: 'input', maxlength: 11, reg: "^1[34578][0-9]{9}$"}
    ],                      
    formData: {
      shopType: '',
      shopName: '',         //商家名称
      industry: '',     //行业分类
      region: '江苏省连云港市连云区',         //所属区域
      adress: '',      //详细地址
      openTime: '',    //营业时间
      sopenTime: '',    //开始营业时间
      eopenTime: '',    //结束营业时间
      contactNum: '',        //联系电话
      productsText: '',       //商家介绍
      shopLogo:'',
      shopQrCode:'',
      shopBanner:'',
      openConfirm:'',
      productsImg: '',
      userId: '',
      enterType: 1
    },
    show: {
      industry: '',
      shopType: ''
    },
    keys: '',
    shopLogo: [],          //shopLogo         商家logo
    shopQrCode: [],        //shopQrCode      微信付款码
    shopBanner: [],        //shopBanner        商家轮播图
    openConfirm: [],        //openConfirm  营业执照
    productsImg: [],        //productsImg  商家展示图      
    items: [
      { name: '1', value: '免费试用6个月',checked: true},
      { name: '2', value: '1年 费用1000元'}
    ],
    modelData: {
      showModal: false,
      signle: true,
      signleBtnTxt: "确定",
      content: '',
    },
    shopTypeData: [{ id: 0, title: '商家' }, { id: 1, title: '企业' }],
    navTopItems: [
      { id: 1, icon: app.globalData.imageUrl + 'ic_gastronomy@2x.png', title: '美食', url: '/pages/hotSeach/hotSeach' },
      { id: 2, icon: app.globalData.imageUrl + 'ic_hotel@2x.png', title: '酒店', url: '/pages/hotSeach/hotSeach' },
      { id: 3, icon: app.globalData.imageUrl + 'ic_fallow@2x.png', title: '休闲娱乐', url: '/pages/hotSeach/hotSeach' },
      { id: 4, icon: app.globalData.imageUrl + 'ic_lido@2x.png', title: '丽人美发', url: '/pages/hotSeach/hotSeach' },
      { id: 5, icon: app.globalData.imageUrl + 'ic_pet@2x.png', title: '宠物', url: '/pages/hotSeach/hotSeach' },
      { id: 6, icon: app.globalData.imageUrl + 'ic_maternal_and_infant@2x.png', title: '母婴', url: '/pages/hotSeach/hotSeach' },
      { id: 7, icon: app.globalData.imageUrl + 'ic_wedding_photography@2x.png', title: '结婚摄影', url: '/pages/hotSeach/hotSeach' },
      { id: 8, icon: app.globalData.imageUrl + 'ic_sports@2x.png', title: '运动健身', url: '/pages/hotSeach/hotSeach' },
      { id: 9, icon: app.globalData.imageUrl + 'ic_auto_service@2x.png', title: '汽车服务', url: '/pages/hotSeach/hotSeach' },
      { id: 10, icon: app.globalData.imageUrl + 'ic_domestic_outfit_building_materials@2x.png', title: '家装建材', url: '/pages/hotSeach/hotSeach' },
      { id: 11, icon: app.globalData.imageUrl + 'ic_education_and_training@2x.png', title: '教育培训', url: '/pages/hotSeach/hotSeach' },
      { id: 12, icon: app.globalData.imageUrl + 'ic_costume@2x.png', title: '服装鞋帽', url: '/pages/hotSeach/hotSeach' },
      { id: 13, icon: app.globalData.imageUrl + 'ic_freight_moving@2x.png', title: '货运搬家', url: '/pages/hotSeach/hotSeach' },
      { id: 14, icon: app.globalData.imageUrl + 'ic_homemaking@2x.png', title: '家政', url: '/pages/hotSeach/hotSeach' },
      { id: 15, icon: app.globalData.imageUrl + 'ic_Industry_resources@2x.png', title: '更多', url: '/pages/hotSeach/hotSeach' }
    ],
    inputShow:'',
    value:'',
    currentInput:'',
    active:'',
    canSubmit: false
  },
  checkReg: function (data) {
    var flag = true;
    for (var i = 0; i < data.length; i++) {
      if (data[i].reg) {
        var reg = new RegExp(data[i].reg);
        if (!reg.test(this.data.formData[data[i].key])) {
          flag = false;
          this.setData({
            'modelData.showModal': true,
            'modelData.content': '请输入正确的' + data[i].label
          });
          return;
        }
      }
    }
    return flag;
  },
  bindInputFunc: function (e) {
    let key = e.currentTarget.dataset.key;
    this.data.formData[key] = e.detail.value;
    this.setData({ formData: this.data.formData });
    this.changeValue();
  },
  radioChange: function (e) {
    this.data.formData.enterType = e.detail.value;
  },
  bindFormSubmit: function (e) {
    var item = this.data.currentInput;
    var flag = true;
    if (this.data.active != '') {
      if (item.reg) {
        var reg = new RegExp(item.reg);
        if (!reg.test(e.detail.value.con)) {
          flag = false;
          this.setData({
            'modelData.showModal': true,
            'modelData.content': '请输入正确的' + item.label
          })
        }
      }
      if (flag) {
        this.data.inputShow = false; 
        this.data.formData[item.key] = e.detail.value.con;
        wx.setNavigationBarTitle({
          title: '入驻商家'
        })
        this.setData({
          inputShow: this.data.inputShow,
          value: '',
          formData: this.data.formData
        })
      }
    }
  },
  //输入框点击事件
  inputTap(e) {
    var item = e.currentTarget.dataset.item;
    this.data.inputShow = true;
    this.data.value = this.data.formData[item.key];
    if (this.data.formData[item.key] == '' && item.isrequire) {
      this.data.active = '';
    } else {
      this.data.active = 'active';
    }
    wx.setNavigationBarTitle({
      title: item.label
    })
    this.setData({
      inputShow: this.data.inputShow,
      value: this.data.value,
      currentInput: item,
      active: this.data.active
    })
    this.changeValue()
  },
  inputRemark: function (e) {
    this.data.formData[e.target.dataset.key] = e.detail.value;
    this.changeValue()
  },
  openText: function (e) {//打开《拼车平台声明》
    wx.navigateTo({
      url: '/pages/text/text?type=2',
    })
  },
  changeTextarea: function (e) {//其他需求textarea值改变事件

      if (e.detail.value == 'false') {
        this.data.isAgree = true;
      } else {
        this.data.isAgree = false;
      }
   
    this.setData({
      isAgree: this.data.isAgree
    })
    this.changeValue();
  },
  changeValue: function () {
    var flag = true;
    var item = this.data.formData; 
    if ((item.shopName === '') || (item.industry === '') || (item.shopType === '') || (item.region === '') || (item.adress === '') || (item.sopenTime === '') || (item.eopenTime === '') || (item.contactNum === '') || (item.productsText === '') || (item.shopLogo === '') || (item.shopBanner === '') || (item.openConfirm === '' || this.data.isAgree==false)) {
        flag = false;
    }
    this.setData({
      canSubmit: flag
    })
  },
  bindPickerChange: function (e) {
    var item = e.target.dataset.item;
    if (e.target.dataset.type != undefined) {
      if (item.mode == 'region'){
        this.data.formData[item.key] = e.detail.value[0] + e.detail.value[1] + e.detail.value[2]
      }
      else{      
        this.data.formData[item.key] = e.detail.value;
      }
    }
    else{
      this.data.show[item.key] = this.data.formlist[e.target.dataset.index].data[e.detail.value].title;
      this.data.formData[item.key] = this.data.formlist[e.target.dataset.index].data[e.detail.value].id;
      var key = 'show.'+item.key;
      this.setData({
        [key]: this.data.formlist[e.target.dataset.index].data[e.detail.value].title
      })
    }

    this.setData({
      formData: this.data.formData
    });
    this.changeValue();
  },
  // 添加图片
  addPhoto: function (e) {
    var that = this,
      count = 0,
      key = e.currentTarget.dataset.id,
    only = e.currentTarget.dataset.only;
    only ? count = 1 : count = 9 - this.data[key].length;
    wx.chooseImage({
      count: count,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        var imgsrc = res.tempFilePaths;
        that.uploadImg(imgsrc, key, 0)
      },
      fail: function () {
        // fail
      },
      complete: function () {
        // complete
      }
    })
  },
  /*上传图片*/
  uploadImg: function (path, key, tag, oIndex) {
    var data1 = app.uploadimg({
      url: app.globalData.httpApiCar + 'uploadfile/upload1',
      path: path,
      globalkey: this,
      realpath: this.data[key],
      showkey: key,
      key: 'formData.'+key,
      tag: tag,
      oIndex: oIndex
    });
  },
  // 修改图片
  changePhoto: function (e) {
    var that = this,
      key = e.currentTarget.dataset.id,
      index = e.currentTarget.dataset.value;
    wx.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: function (res) {
        var imgsrc = res.tempFilePaths;
        that.uploadImg(imgsrc, key, 1, index)
      },
      fail: function () {
        // fail
      },
      complete: function () {
        // complete
      }
    })
  },
  delImg: function (e) {
    var key = e.currentTarget.dataset.id,
      index = e.currentTarget.dataset.value;
    this.data[key].splice(index, 1);
    this.setData({
      [key]: this.data[key],
      ['formData.'+key]: this.data[key].join(",")
    });
    this.changeValue();
  },
  // 入驻商家表格提交
  bindrzFormSubmit: function () {
    if (this.data.canSubmit) {
      if (this.checkReg(this.data.formlist) == true){
        if (wx.getStorageSync('ShopId') == '') {
          var _this = this;
          _this.setData({
            canSubmit: false
          })
          this.data.formData.openTime = this.data.formData.sopenTime + '-' + this.data.formData.eopenTime;
          wx.request({
            url: app.globalData.httpApiCar + 'shopInfo/save',
            method: 'POST',
            data: this.data.formData,
            header: {
              'content-type': 'application/x-www-form-urlencoded' // 默认值
            },
            success: function (res) {
              if (res.data.success) {
                if (_this.data.formData.enterType == 2){
                  _this.selectPay(res.data.data)
                }
                else{
                  _this.getIsShop();
                  wx.navigateBack()
                }
              }
            }
          })
        }
        else {
          wx.showToast({
            title: '您已入驻商家',
            icon: 'none',
            duration: 2000
          })
          // wx.navigateTo({
          //   url: '/pages/',
          // })
        }
      }
    }
  },
  selectPay: function(id){
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'shopOrder/payTheBillToGY',
      data: { backupE: id, userId: _this.data.userInfo.id, openId: app.globalData.openId},
      success: function (res) {
        if (res.data.success) {
          _this.requestPayment(res.data.data,id);
        }
      }
    })
  },
  requestPayment: function (obj,id) {
    var that = this;
    wx.requestPayment({
      'timeStamp': obj.timeStamp,
      'nonceStr': obj.nonceStr,
      'package': obj.package,
      'signType': obj.signType,
      'paySign': obj.paySign,
      'success': function (res) {
        that.getIsShop();
        wx.navigateBack()
      },
      'fail': function (res) {
        that.deleteShop(id)
      }
    })
  },
  deleteShop: function(id){
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'shopInfo/deleteByPrimaryKey',
      data: { id: id},
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      success: function (res) {
        if (res.data.success) {
          wx.showModal({
            title: '提示',
            content: '支付失败',
            showCancel: false,
            success: function (res) {
              if (res.confirm) {
                _this.getIsShop();
                wx.navigateBack()
              }
            }
          })
        }
      }
    })
  },
  getIsShop: function () {
    var id = JSON.parse(wx.getStorageSync('userInfo')).id;
    var _this = this;
    wx.request({
      url: app.globalData.httpApiCar + 'shopInfo/getOne',
      data: {
        userId: id
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        
        if (!res.data.success) {
          wx.setStorageSync('isShop', '0');
          wx.removeStorageSync('ShopId');
        }
        else {
          wx.setStorageSync('isOut', res.data.data.dateFlag);
          if (res.data.data.status == 1) {
            wx.setStorageSync('isShop', '2');
          }
          else {
            wx.setStorageSync('isShop', '1');
            wx.setStorageSync('ShopId', res.data.data.data.id);
          }
        }
        _this.setData({
          isShop: wx.getStorageSync("isShop")
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    model.init.apply(this, ['modelData']);
    var key1 = 'formData.userId';
    
    this.setData({
      [key1]: JSON.parse(wx.getStorageSync('userInfo')).id,
      userInfo: JSON.parse(wx.getStorageSync('userInfo'))
    })

    //wx.clearStorage();
  },
  bindobj: function (oldval, newval, key, index) {
    var arr = [];
    arr = this.data[oldval];
    arr[index][key] = newval;
    this.setData({
      formlist: arr
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    
    //wx.clearStorage();
    this.bindobj('formlist', this.data.shopTypeData, 'data', 0);
    this.bindobj('formlist', this.data.navTopItems, 'data', 2);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})